import os
from tkinter import simpledialog
import time
import uuid
import pyautogui
import sys
import mwindow
from pynput.keyboard import Controller, Key, Listener
import win32gui
import win32con
from enum import Enum
import trainee
from scores.scorea import CalcA
from traineeskill import ts

def DragMouse(x1:int,y1:int,x2:int,y2:int):
    pyautogui.moveTo(x1, y1)
    pyautogui.dragTo(x2, y2, 0.3, button='left')

class FsmState:
    def __init__(self,count:int):
        self.auto_flag = False #0-指定个数 1-自动判断个数
        self.trainee_count = count
        if self.trainee_count == 0:
            self.auto_flag = True

        self.state = 0 #0-浏览界面 1-学徒界面
        self.auto_try_count = 0 #尝试次数
        self.auto_index = 0 #处理其它行的索引
        self.auto_last_trainee = '' #最后一个学徒的名字
        self.trainee_index = 0
        self.drag_init_count = 0 #用于回到起始位置的拖动次数

class Operate:
    def __init__(self,mset:mwindow.MWindowSet,trainee_count:int):
        self.fsmstate = FsmState(trainee_count)
        self.trainee_infos = {}
        self.quality = ''
        self.startt = time.perf_counter()
        self.exist_count = 0
        self.process_count = 0
        self.traineeInfo = trainee.Trainee()
        self.mset = mset

    def PrintTime(self):
        t = time.perf_counter()
        dt = t - self.startt
        print(f'ontimer: 执行了{dt/60}分钟, fsmstate={self.fsmstate.state},进度:{self.fsmstate.trainee_index}/{self.fsmstate.trainee_count},已忽略{self.exist_count}')
        # if fsmstate.trainee_index == fsmstate.trainee_count:
        #     print(f'ontimer: 平均每个学徒耗费{dt/(60*fsmstate.trainee_count)}分钟')

    def RemoveNeedlessImg(self):
        directory = f'./capture/{self.quality}'
        for filename in os.listdir(directory):
            file_path = os.path.join(directory, filename)
            if not os.path.isfile(file_path):
                continue
            ss = filename.split('_')
            b_needremove = True
            if len(ss) >= 2:
                id = "_".join(ss[:2])
                if id in self.trainee_infos:
                    b_needremove = False
            if b_needremove:
                os.remove(file_path)
                print(f"Deleted file: {file_path}")
            
    def SelectTrainee(self,win:mwindow.MWindow):
        if self.fsmstate.state == 0:
            if self.quality == '':
                self.quality = win.GetLabelText('品质')
            self.fsmstate.state = 1
            if self.fsmstate.auto_flag:
                if self.fsmstate.auto_index < 3:
                    pos = [win.region[0] + 81,win.region[1] + 470 + self.fsmstate.auto_index * 134]
                    print(f'click: pos={pos},auto_index={self.fsmstate.auto_index},win={win.region}')
                    pyautogui.click(pos[0],pos[1])
                    if self.fsmstate.auto_index > 0:
                        self.fsmstate.auto_index += 1
                else:
                    print('结束')
                    self.RemoveNeedlessImg()
                    exit(0)
            else:
                if self.fsmstate.trainee_index >= self.fsmstate.trainee_count:
                    print('结束')
                    self.RemoveNeedlessImg()
                    exit(0)
                self.fsmstate.state = 1
                if self.fsmstate.trainee_count <= 3:
                    offset = self.fsmstate.trainee_index
                else:
                    offset = self.fsmstate.trainee_index - (self.fsmstate.trainee_count - 3)
                    if offset < 0:
                        offset = 0
                self.fsmstate.trainee_index += 1 
                pos = [win.region[0] + 81,win.region[1] + 470 + offset * 134]
                print(f'click: pos={pos},offset={offset},win={win.region},offset={offset}')
                pyautogui.click(pos[0],pos[1])
        else:
            bdrag:bool = False
            if self.fsmstate.auto_flag:
                bdrag = (self.fsmstate.auto_index == 0)
            else:
                offset = self.fsmstate.trainee_index - (self.fsmstate.trainee_count - 3)
                bdrag = (offset <= 0)
            if bdrag:
                DragMouse(win.region[0] + 232,win.region[1] + 472+152,win.region[0] + 232,win.region[1] + 472)
            self.traineeInfo.Clear()
            self.fsmstate.state = 0
            self.fsmstate.drag_init_count = 0

    def CaptureTraineeSkills(self,win:mwindow.MWindow):
        if len(self.traineeInfo.name) == 0:
            name = win.GetLabelMultiText('名称')
            self.traineeInfo.SetName(name)
        if len(self.traineeInfo.genius) == 0:
            genius = win.GetLabelMultiText('天赋')
            self.traineeInfo.SetGenius(genius)
        if self.traineeInfo.imginfos == None:
            inforegion = win.GetLabelImg('信息综合')
            self.traineeInfo.SetImgInfos(inforegion)
        skill = win.GetLabelText('技能',multiline=True)
        self.traineeInfo.AddSkill(skill)
        if len(self.traineeInfo.skills) == 20:
            self.process_count += 1
            print(f'完成20个技能, 处理个数{self.process_count}')
            CalcA(ts,self.traineeInfo)
            self.traineeInfo.GenCsv(self.quality)
            self.traineeInfo.GenImg(self.fsmstate.trainee_index,self.quality)
            win.ClickLabel('退出')
            return
        print(f'drag begin:{len(self.traineeInfo.skills)}')
        DragMouse(win.region[0] + 312,win.region[1] + 678,win.region[0] + 211,win.region[1] + 678)
        print('drag end')

    def DoMain(self):
        win = self.mset.CheckWindow()
        if win != None:
            if win.name == "学徒浏览":
                self.SelectTrainee(win)
            elif win.name == "学徒进阶":
                brepeat = False
                if len(self.traineeInfo.infos) == 0:
                    tests = win.GetLabelMultiText('信息面板')
                    self.traineeInfo.SetInfos(tests)
                    if self.fsmstate.auto_flag:
                        traineeid = self.traineeInfo.GetId()
                        self.trainee_infos[self.traineeInfo.GetId()] = ""
                        brepeat = (self.fsmstate.auto_last_trainee != '' and traineeid == self.fsmstate.auto_last_trainee)
                        if brepeat:
                            self.fsmstate.auto_try_count += 1
                            print(f'名字重复:{traineeid},{self.fsmstate.auto_try_count}次')
                            if self.fsmstate.auto_try_count > 3:
                                print(f'重复名字超过3次')
                                self.fsmstate.auto_index += 1
                            win.ClickLabel('退出')
                        else:
                            self.fsmstate.auto_try_count = 0
                            self.fsmstate.auto_last_trainee = traineeid
                            print(f'set last={self.fsmstate.auto_last_trainee}')
                if not brepeat:
                    if win.ExistLabel('锁'):
                        self.traineeInfo.SetLock(True)
                    else:
                        self.traineeInfo.SetLock(False)
                    if not self.traineeInfo.CheckExist(self.quality):
                        if self.fsmstate.drag_init_count == 0:
                            print(f'ontimer: 技能表回归原位')
                            for i in range(3):
                                DragMouse(win.region[0] + 100,win.region[1] + 678,win.region[0] + 424,win.region[1] + 678)
                            self.fsmstate.drag_init_count = 1
                        else:
                            self.CaptureTraineeSkills(win)
                    else:
                        self.exist_count += 1
                        self.process_count += 1
                        print(f'{self.traineeInfo.GetId()}已存在,处理个数{self.process_count}')
                        win.ClickLabel('退出')
            else:
                print('没有找到学徒进阶界面')
                exit(0)
        else:
            print("未检测到窗体")
            exit(0)
